package com.loiot.baqi.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.loiot.baqi.constant.Const;
import com.loiot.baqi.constant.URLConst;
import com.loiot.baqi.controller.response.AjaxResponse;
import com.loiot.baqi.controller.response.Pager;
import com.loiot.baqi.pojo.TgProduct;
import com.loiot.baqi.pojo.TgProductSetting;
import com.loiot.baqi.service.TgProductService;
import com.loiot.baqi.service.TgProductSettingService;
import com.loiot.commons.message.util.JsonUtil;
import com.timeloit.pojo.Account;

/**
 * 建议 处理器。 TgProductSetting
 * 
 * @author Hinsteny
 * @creation 2016-03-07
 */

@Controller
@RequestMapping(value = "/tgProductSetting")
public class TgProductSettingController {

	public static final AjaxResponse NAME_EXIST = new AjaxResponse(-100, "建议已存在");

	private static Logger logger = LoggerFactory.getLogger(TgProductSettingController.class);

	@Resource
	private TgProductService tgProductService;

	@Resource
	private TgProductSettingService tgProductSettingService;

	private HashMap<String, Object> pmap = new HashMap<String, Object>();

	/**
	 * 跳转 礼品列表页
	 * 
	 * @return 模板位置
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/list")
	public String list(@RequestParam(value = "pi", defaultValue = "0") int pageIndex,
			@RequestParam(value = "jsonParam", defaultValue = "{}") String jsonParam, TgProductSetting p,
			ModelMap model) throws Exception {
		HashMap<String, Object> paramMap = JsonUtil.toObject(jsonParam, HashMap.class);
		paramMap.put("qtype", "like");
		Pager<TgProductSetting> pager = tgProductSettingService.queryTgProductSettingListPage(paramMap, pageIndex);
		model.put("pager", pager);
		model.put("jsonParam", jsonParam);
        putJsonParamIntoModle(paramMap, model);
		return "/productSetting/productSetting_list";
	}

	/**
	 * 跳转到添加页面
	 * 
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/toAdd")
	public String toAddTgProductSetting(@RequestParam(value = "pi", defaultValue = "0") int pageIndex,
			@RequestParam(value = "jsonParam", defaultValue = "{}") String jsonParam, TgProductSetting p,
			ModelMap model) throws Exception {
		HashMap<String, Object> paramMap = JsonUtil.toObject(jsonParam, HashMap.class);
		if(paramMap.get("start_price") != null){
			String startPrice = paramMap.get("start_price").toString();
			try {
				Long sPrice = Long.valueOf(startPrice);
				paramMap.put("start_price", sPrice);
			} catch (Exception e) {
				paramMap.put("start_price", null);
			}
		}
		if(paramMap.get("end_price") != null){
			String endPrice = paramMap.get("end_price").toString();
			try {
				Long ePrice = Long.valueOf(endPrice);
				paramMap.put("end_price", ePrice);
			} catch (Exception e) {
				paramMap.put("end_price", null);
			}
		}
		paramMap.put("qtype", "like");
		paramMap.put("isSetting", "true");
		Pager<TgProduct> pager = tgProductService.queryTgProductListPage(paramMap, pageIndex);
		model.put("pager", pager);
        putJsonParamIntoModle(paramMap, model);
        List<HashMap<String,Object>> productSettings = tgProductSettingService.queryTgProductSettingAllInfoList(new HashMap<String, Object>());
		model.put("productSettings", productSettings);
		return "/productSetting/productSetting_add";
	}

	/**
	 * 添加 建议
	 * 
	 * @param p
	 *            对象参数
	 * @return ajax响应
	 */
	@RequestMapping(value = "/add")
	@ResponseBody
	public Object addTgProductSetting(TgProductSetting p, HttpSession session, HttpServletRequest request) {

		try {
			Account account = (Account) session.getAttribute(Const.SESSION_USER_KEY);
			// 验证唯一性
			pmap.clear();
			pmap.put("productId", p.getProductId());
			int result = tgProductSettingService.getTgProductSettingListCount(pmap);
			if (result > 0) {
				return NAME_EXIST;
			}
			p.setInTime(new Date());
			p.setInPerson(account.getAccountId());
			tgProductSettingService.addTgProductSetting(p);
			// 添加成功
			return AjaxResponse.OK;
		} catch (Exception e) {
			e.printStackTrace();
			// 失败
			return AjaxResponse.FAILED;
		}

	}

	/**
	 * 跳转到编辑页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/toEdit")
	public String toEditTgProductSetting(@RequestParam(value = "id", required = true) java.lang.Long id, ModelMap model)
			throws Exception {
		if (id == null) {
			return URLConst.ERROR_URL;
		}
		model.put("pid", id);
		model.put("p", tgProductSettingService.getTgProductSettingById(id));
		return "/productSetting/productSetting_add";
	}

	/**
	 * 更新 建议
	 * 
	 * @param p
	 *            对象参数
	 * @return ajax响应
	 */
	@RequestMapping(value = "/edit")
	@ResponseBody
	public Object editTgProductSetting(HttpSession session, HttpServletRequest request, @RequestBody TgProductSetting p) {
		try {
			// 获得账号
			Account account = (Account) session.getAttribute(Const.SESSION_USER_KEY);
			p.setUpdateTime(new Date());
			p.setUpdatePerson(account.getAccountId());
			tgProductSettingService.updateTgProductSetting(p);
		} catch (Exception e) {
			e.printStackTrace();
			return AjaxResponse.FAILED;
		}
		return AjaxResponse.OK;
	}

	/**
	 * 跳转到查看页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/toView")
	public String toViewTgProductSetting(@RequestParam(value = "id", required = true) java.lang.Long id, ModelMap model)
			throws Exception {
		if (id == null) {
			return URLConst.ERROR_URL;
		}
		// model.put("p", tgProductSettingService.getTgProductSettingById(id));
		model.put("pid", id);
		return "/productSetting/productSetting_add";
	}

	/**
	 * 删除 建议
	 * 
	 * @param id
	 *            TgProductSettingID
	 */
	@RequestMapping(value = "/delete")
	public String deleteTgProductSetting(@RequestParam(value = "id", required = true) java.lang.Long id,
			HttpServletRequest request) throws Exception {
		tgProductSettingService.deleteTgProductSetting(id);
		String s = request.getHeader("Referer");
		String redirectStr = s.substring(s.indexOf("/tgProductSetting/"), s.length());
		return "redirect:" + redirectStr;
	}

	/**
	 * ajax删除 建议
	 * 
	 * @param id
	 *            TgProductSettingID
	 */
	@RequestMapping(value = "/ajaxDelete")
	@ResponseBody
	public Object ajaxDeleteTgProductSetting(@RequestParam(value = "id", required = true) java.lang.Long id) {
		try {
			TgProductSetting p = new TgProductSetting();
			p.setId(id);
			tgProductSettingService.deleteTgProductSetting(p);
			return AjaxResponse.OK;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return AjaxResponse.FAILED;
		}
	}

	/**
	 * ajax 根据id查询实体bean
	 * 
	 * @return
	 */
	@RequestMapping(value = "/addList")
	@ResponseBody
	public Object addList(HttpSession session, @RequestBody java.lang.Long[] ids) throws Exception {
		Account account = (Account) session.getAttribute(Const.SESSION_USER_KEY);
		Long accountId = account != null ? account.getAccountId() : 0;
		int result = tgProductSettingService.addTgProductSettingList(ids, accountId);
		return AjaxResponse.OK(result);
	}

	/**
	 * ajax 根据id查询实体bean
	 * 
	 * @return
	 */
	@RequestMapping(value = "/removeList")
	@ResponseBody
	public Object removeList(@RequestBody java.lang.Long[] ids) throws Exception {
		int result = tgProductSettingService.removeTgProductSettingList(ids);
		return AjaxResponse.OK(result);
	}
	
    /**
     * 把客户端的查询参数放置到model中，方便页面获取
     * 
     * @param paramMap
     * @param model
     */
    @SuppressWarnings("rawtypes")
    public void putJsonParamIntoModle(Map paramMap, ModelMap model) {
        if (paramMap == null || paramMap.size() == 0)
            return;
        Iterator iter = paramMap.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Object key = entry.getKey();
            Object val = entry.getValue();
            model.put(String.valueOf(key), val);
        }
    }

}
